//
//  ViewController.m
//  4-RunLoop
//
//  Created by J on 16/1/25.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self observer];
    [self timer];
    
   }


- (void)observer{
    
    /* Run Loop Observer Activities */
    typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
        kCFRunLoopEntry = (1UL << 0),//2^0 = 1//即将进入Loop
        kCFRunLoopBeforeTimers = (1UL << 1),//2^1 = 2//即将处理Timer
        kCFRunLoopBeforeSources = (1UL << 2),//2^2 = 4//即将处理Source
        kCFRunLoopBeforeWaiting = (1UL << 5),//2^5 = 32//即将进入休眠
        kCFRunLoopAfterWaiting = (1UL << 6), //2^6 = 64//刚从休眠中唤醒
        kCFRunLoopExit = (1UL << 7), //2^7 = 128//即将退出Loop
        kCFRunLoopAllActivities = 0x0FFFFFFFU
    };
    //添加观察者:监听RunLoop状态 CFRunLoopGetCurrent()当前runloop
    CFRunLoopObserverRef observer =  CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        
        NSLog(@"%zd",activity);
    });
    
    //添加observer
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
    //释放Observer
    //CF的内存管理 (Core Foundation)
    //1.凡是带有Create 、 Copy 、 Retain等的函数创建出来的对象都需要在最后做一次release
    //*比如
    //2.release函数: CFRelease(对象)
    CFRelease(observer);//observer不是oc对象 所以需要手动释放

    
}
- (void)timer2{
    //    CADisplayLink* link;
    //    - (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSString *)mode;

    //调用了scheduledTimer返回的定时器 已经自动被添加到当前runLoop中 而且默认kCFRunLoopDefaultMode
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(Log) userInfo:nil repeats:YES];
    
    //修改模式
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];

}
- (IBAction)click:(UIButton *)sender {
    NSLog(@"sender");
}

- (void)timer{//NSTimer不同模式工作
    //这种方式创建的 NSTimer是一个纯净的timer并没有被添加到runloop中
    NSTimer* timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(Log) userInfo:nil repeats:YES];
    
    
    //    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];//只有NSDefaultRunLoopMode模式定时器才会起作用 当我拖动textView的时候自动切换到UITrackingRunLoopMode 模式 不拖动的时候又会恢复到 NSDefaultRunLoopMode模式 同时只能在一种模式工作
    
    //    [[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];//定时器只在UITrackingRunLoopMode模式工作
    
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];//包含forMode:UITrackingRunLoopMode||UITrackingRunLoopMode模式都能工作(同时只能一种)

    
}
- (void)Log{
    
    NSLog(@"---%@",[NSRunLoop currentRunLoop].currentMode);
}


@end
